package ordinaryArray;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/*
 * description 文本对齐
 * author hkfan
 * version 1.0
 * create 2025/5/27 15:30
 */
public class LeetCode_68 {

    @Test
    public void test(){
        List<String> strings = fullJustify(new String[]{"ask","not","what","your","country","can","do","for","you","ask","what","you","can","do","for","your","country"}, 16);
        for (String string : strings) {
            System.out.println(string+"   "+string.length());
        }
    }

    public List<String> fullJustify(String[] words, int maxWidth) {
        //1. 定义参数
        int size = 0;
        String str = "";
        List<String> list = new ArrayList<>();
        //2. 循环划分字符
        for (int i = 0; i < words.length; i++) {
            if ((size+words[i].length()<=maxWidth)||(size==0&&words[i].length()<=maxWidth)){
                size=size+words[i].length()+1;
                str=str+words[i]+" ";
            }else {
                list.add(str.trim());
                i--;
                str="";
                size=0;
            }
        }
        list.add(str);
        //3. 添加空格
        for (int i = 0; i < list.size()-1; i++) {
            String[] trs = list.get(i).split(" ");
            int width=maxWidth;
            for (String tr : trs) {
                width-=tr.length();
            }
            String tempStr = "",blank="";
            int count1=0,count2=0,m=0,k=1;
            if (trs.length!=1){
                count1 = width/(trs.length-1);
                count2 = width%(trs.length-1);
                for (int j = 0; j < count1; j++) {
                    blank+=" ";
                }
            }

            while (m < trs.length-1) {
                tempStr+=trs[m]+blank;
                if (k<=count2){
                    k++;
                    tempStr+=" ";
                }
                m++;
            }
            tempStr+=trs[m];
            for (int t = tempStr.length(); t < maxWidth ; t++) {
                tempStr+=" ";
            }
            list.set(i,tempStr);
        }
        String s = list.get(list.size() - 1).trim();
        for (int i = s.length(); i < maxWidth ; i++) {
            s+=" ";
        }
        list.set(list.size() - 1,s);
        return list;

    }



}
